package com.onepice.mlp.api.webservice;

import com.alibaba.fastjson.JSONObject;
import com.onepice.mlp.api.common.CommonForUser;
import com.onepice.mlp.api.config.ServerConfig;
import com.onepice.mlp.api.config.UserProfile;
import com.onepice.mlp.core.service.MenuService;
import com.onepice.mlp.data.entity.Menu;
import com.onepice.mlp.utils.commom.ConvUtil;
import com.onepice.mlp.utils.commom.ResponseResult;
import com.onepice.mlp.utils.enums.CodeType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author FireWang
 * @date 2020/12/22 15:06
 * 平台公共接口
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping(value = "/webservice/common")
public class Common {
    private ServerConfig serverConfig;
    private MenuService menuService;

    //返回结果对象
    private static JSONObject resJson;

    /**
     * 接口获取系统版本信息
     *
     * @return
     */
    @RequestMapping(value = "/getVersion", method = RequestMethod.GET)
    public JSONObject getVersion() {
        try {
            resJson = ResponseResult.build(CodeType.SUCCESS, "获取版本信息成功！");
            resJson.put("version", serverConfig.getVersionInfo());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            resJson = ResponseResult.build(CodeType.FAIL, "无法获取版本信息！");
        }
        return resJson;
    }

    /**
     * 接口获取用户菜单
     *
     * @return
     */
    @RequestMapping(value = "/getUserMenu", method = RequestMethod.GET)
    public JSONObject getUserMenu(HttpServletRequest request) {
        try {
            //获取当前用户信息
            UserProfile userProfile = CommonForUser.getUserProfile(request);

            //获取用户权限，也就是可查看的页面
            List<Menu> menuList;
            if (userProfile.isTheAdmin()) {
                menuList = menuService.getAll();
            } else {
                menuList = new ArrayList<>();
                String[] menuIds = userProfile.getRolePermission().split(",");
                for (String menuId : menuIds) {
                    menuList.add(menuService.getById(ConvUtil.convToInt(menuId)));
                }
            }
            resJson = ResponseResult.build(CodeType.SUCCESS, "获取用户菜单成功！");
            resJson.put("menuList", menuList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            resJson = ResponseResult.build(CodeType.FAIL, "无法获取用户菜单！");
        }
        return resJson;
    }
}
